package servlet;

import bean.Book;
import dao.BookDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "InsertBookServlet", value = "/InsertBookServlet")
public class InsertBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

        response.setContentType("text/html;charset=utf-8");
//1.将提交的数据封装到Book 对象(此处new 对象需要在Book 类中提供六个参数的构造方法)
        String bookName = request.getParameter("bookName");
        String author = request.getParameter("author");
        String press = request.getParameter("press");
        String isbn = request.getParameter("isbn");
        String category = request.getParameter("category");
        String price1 = request.getParameter("price");
        Float price = Float.parseFloat(price1);
// 需在book.domain.Book 类中添加带参数的构造方法，以初始化时对象直接赋值。
        Book book = new Book(bookName, author, press, isbn, category, price);
//2.将Book 对象插入到book 表中
        BookDao bookDao = new BookDao();
        boolean flag = bookDao.insertBook(book);
//3.请求转发到/listBooks,显示所有图书
        if (flag) {
            request.setCharacterEncoding("utf-8");
            request.getRequestDispatcher("/ListBookServlet").forward(request, response);
        } else {
            request.setAttribute("insertMsg", "添加图书失败");

            request.getRequestDispatcher("/add.jsp").forward(request, response);
        }
    }
}
